layui.define(['backend', 'notice'], function(exports) {
    "use strict";

    var MOD_NAME = 'gateway',
        backend = layui.backend,
        notice = layui.notice;

    var Ws = {
        client_id : null,
        websocketObj : null,
        init : function () {
            if (!("WebSocket" in window)) {
                notice.warning("您的浏览器不支持 WebSocket!");
                return false;
            }

            backend.api.ajax('/admin/commond/getconfig', function (data) {
                // 打开一个 web socket
                Ws.websocketObj = new WebSocket("ws://" + data.domain + ":" + data.port);

                Ws.websocketObj.onopen = function(event) {
                    Ws.event("open", event);
                };
                Ws.websocketObj.onmessage = function (event) {
                    Ws.event("message", event);
                    var data = Ws.receivedMsg(event);
                    if (data != false && data.event != undefined) {
                        Ws.event(data.event, data.data);
                    }
                };
                Ws.websocketObj.onerror = function (event) {
                    Ws.event("error", event);
                    notice.error("传输发送错误:" + event);
                };
                Ws.websocketObj.onclose = function (event) {
                    Ws.event("close", event);
                };
                return false;
            });
        },
        receivedMsg : function (event) {
            try {
                return eval("(" + event.data + ")");
            }catch (e) {
                return false;
            }
        },
        on : function(events, callback){
            return layui.onevent(MOD_NAME, events, callback);
        },
        event: function (name, data) {
            return layui.event(MOD_NAME, name, data);
        },
        sendMsg : function (type, data) {
            var sendData = {
                type : type,
                data : data
            };
            Ws.websocketObj.send(JSON.stringify(sendData));
        }
    };

    Ws.on('get_client_id', function (data) {
        Ws.client_id = data.client_id;
        Ws.event("beforeBindwk", Ws.client_id);
        backend.api.ajax({
            url : "/admin/index/bindwk",
            data : data
        }, function (backData) {
            Ws.event("afterBindwk", Ws.client_id);
            Ws.sendMsg('login', {token : backData.token})
            return false;
        })
    });

    exports(MOD_NAME, Ws);
});
